package com.zx.ishopping.mapper;

import com.github.pagehelper.Page;
import com.zx.ishopping.DTO.GetOrderListDTO;
import com.zx.ishopping.DTO.OrderPageDTO;
import com.zx.ishopping.VO.OrderVo;
import com.zx.ishopping.annotation.AutoFill;
import com.zx.ishopping.entity.Order;
import com.zx.ishopping.entity.OrderStatusCount;
import com.zx.ishopping.enums.OperationEnum;
import org.apache.ibatis.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface OrderMapper {


    /**
     * 分页查询
     *
     * @param orderPageQueryDTO
     * @return
     */
    Page<OrderVo> pageQuery(OrderPageDTO orderPageQueryDTO);

    /**
     * 根据id查询订单
     * @param id
     * @return
     */
    @Select("select * from orders where id = #{id}")
    Order getById(Long id);

    /**
     * 删除订单
     * @param id
     */
    @Delete("delete from orders where id = #{id}")
    void deleteOrder(Long id);

    /**
     * 修改订单
     * @param order
     */
    @AutoFill(OperationEnum.UPDATE)
    void updateOrder(Order order);

    /**
     * 修改订单状态
     * @param status
     */
   
    @Update("update orders set status = #{status},update_time = now() where id = #{id}")
    void updateOrderStatus(Integer status,Long id);

    /**
     * 根据状态查询订单数量
     * @return
     */
    @Select("SELECT " +
            "status, " +
            "COUNT(*) as count, " +
            "CASE status " +
            "   WHEN 0 THEN '待付款' " +
            "   WHEN 1 THEN '已付款' " +
            "   WHEN 2 THEN '已发货' " +
            "   WHEN 3 THEN '已完成' " +
            "   WHEN 4 THEN '已取消' " +
            "   ELSE '未知状态' " +
            "END as statusName " +
            "FROM orders " +
            "GROUP BY status")
    List<OrderStatusCount> getOrderCountByStatus();

    /**
     * 获取超时订单
     * @param expireTime
     * @param status
     * @return
     */
    @Select("select * from orders where status = 0 and create_time < #{expireTime}")
    List<Order> queryExpireOrderList(LocalDateTime expireTime, int status);

    /**
     * 修改订单状态和下单时间
     * @param status
     * @param id
     */
    
    @Update("update orders set status = #{status},create_time = now(),update_time = now() where id = #{id}")
    void updateOrderStatusAndCreateTime(Integer status, Long id);

    /**
     * 根据用户id查询不同状态的商品订单
     * @param getOrderListDTO
     * @return
     */
    List<OrderVo> getOrderList(GetOrderListDTO getOrderListDTO);

    /**
     * 添加订单
     * @param order
     */
    @AutoFill(OperationEnum.INSERT)
    
    void addOrder(Order order);
}
